<template>
  <el-dialog
    v-model="visible"
    title="新建项目"
    width="900px"
    :before-close="handleClose"
    class="create-project-dialog"
    :lock-scroll="true"
    :modal="true"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <!-- 创建空白项目 -->
    <div class="create-blank-section">
      <div class="blank-project-card" @click="handleCreateBlank">
        <div class="blank-icon">
          <el-icon size="12">
            <Plus />
          </el-icon>
        </div>
        <span class="blank-text">创建空白项目</span>
      </div>
    </div>

    <!-- 模板选择区域 -->
    <div class="template-section">
      <div class="section-header">
        <span class="section-title">选择以下模版新建项目：</span>
        <div text class="template-manage-btn" @click="handleManageTemplates">
          <img :src="IconTools" alt="工具" class="tools-icon" />
          模版管理
        </div>
      </div>

      <div
        class="template-grid-container"
        ref="templateGridRef"
        @scroll="handleScroll"
        v-loading="loading"
      >
        <div class="template-grid">
          <div
            v-for="template in templateList"
            :key="template.id"
            class="template-card"
            @click="handleSelectTemplate(template)"
          >
            <div class="template-preview">
              <img :src="template.cover" v-if="template.cover" />
              <div class="template-bg" v-else>
                <img class="template-bg-icon" :src="TemplateBg" />
              </div>
            </div>
            <div class="template-info">
              <h4 class="template-name">{{ getTemplateName(template) }}</h4>
              <p class="template-description">{{ template.remark }}</p>
            </div>
          </div>
        </div>

        <!-- 加载更多指示器 -->
        <div v-if="loadingMore" class="loading-more">
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          <span>加载更多...</span>
        </div>

        <!-- 没有更多数据提示 -->
        <div v-else-if="!hasMore && templateList.length > 0" class="no-more">
          <span>已加载全部模板</span>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, watch, onUnmounted } from "vue";
  import { ElDialog, ElIcon, ElMessage } from "element-plus";
  import { Plus, Loading } from "@element-plus/icons-vue";
  import IconTools from "@/assets/icon-tools.svg";
  import { getProjectTemplates } from "@/api/template";
  import type { ProjectTemplateVO } from "@/interface/project";
  import TemplateBg from "@/assets/template-bg.svg";

  interface CreateProjectTemplatesDialogProps {
    modelValue: boolean;
  }

  const props = withDefaults(defineProps<CreateProjectTemplatesDialogProps>(), {
    modelValue: false,
  });

  const emit = defineEmits<{
    (e: "update:modelValue", value: boolean): void;
    (e: "create-blank"): void;
    (e: "select-template", template: ProjectTemplateVO): void;
    (e: "manage-templates"): void;
  }>();

  const visible = ref(false);
  const loading = ref(false);
  const loadingMore = ref(false);
  const templateList = ref<ProjectTemplateVO[]>([]);
  const currentPage = ref(1);
  const pageSize = ref(5);
  const total = ref(0);
  const hasMore = ref(true);
  const templateGridRef = ref<HTMLElement>();

  // 获取模板名称
  const getTemplateName = (template: ProjectTemplateVO): string => {
    if (typeof template.name === "object" && template.name) {
      return template.name["zh-CN"] || template.name["en"] || "未命名模板";
    }
    return template.name || "未命名模板";
  };

  // 获取项目模板列表
  const fetchTemplates = async (reset = true) => {
    if (reset) {
      loading.value = true;
      currentPage.value = 1;
      templateList.value = [];
    } else {
      loadingMore.value = true;
    }

    try {
      const response = await getProjectTemplates({
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        // conditions: [],
        // logic: "AND",
        // sortParams: [
        //   {
        //     field: "modifyTime",
        //     asc: false,
        //   },
        // ],
      });

      const responseData = (response as any).data || response;
      const result = responseData.result || [];
      const convertedTemplates = result;

      if (reset) {
        templateList.value = convertedTemplates;
      } else {
        templateList.value.push(...convertedTemplates);
      }

      total.value = responseData.total || 0;
      hasMore.value = templateList.value.length < total.value;

      if (convertedTemplates.length === 0 && reset) {
        console.warn("未获取到项目模板数据");
      }
    } catch (error) {
      console.error("获取项目模板失败:", error);
      ElMessage.error("获取项目模板失败");
    } finally {
      if (reset) {
        loading.value = false;
      } else {
        loadingMore.value = false;
      }
    }
  };

  // 加载更多模板
  const loadMoreTemplates = async () => {
    if (loadingMore.value || !hasMore.value) return;

    currentPage.value += 1;
    await fetchTemplates(false);
  };

  // 滚动事件处理
  const handleScroll = (event: Event) => {
    const target = event.target as HTMLElement;
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;

    // 当滚动到底部附近时加载更多
    if (
      scrollTop + clientHeight >= scrollHeight - 100 &&
      hasMore.value &&
      !loadingMore.value
    ) {
      loadMoreTemplates();
    }
  };

  // 监听 modelValue 变化
  watch(
    () => props.modelValue,
    (newValue) => {
      visible.value = newValue;
      handleBodyScroll(newValue);
      // 弹窗打开时获取模板数据
      if (newValue) {
        fetchTemplates(true);
      }
    },
  );

  // 监听 visible 变化
  watch(visible, (newValue) => {
    emit("update:modelValue", newValue);
    handleBodyScroll(newValue);
  });

  // 控制body滚动
  const handleBodyScroll = (isVisible: boolean) => {
    const body = document.body;
    if (isVisible) {
      // 禁止body滚动
      body.style.overflow = "hidden";
      body.style.paddingRight = "0px";
    } else {
      // 恢复body滚动
      body.style.overflow = "";
      body.style.paddingRight = "";
    }
  };

  const handleClose = () => {
    visible.value = false;
    handleBodyScroll(false);
  };

  const handleCreateBlank = () => {
    console.log("CreateProjectTemplatesDialog: 点击创建空白项目");
    emit("create-blank");
    handleClose();
  };

  const handleSelectTemplate = (template: ProjectTemplateVO) => {
    emit("select-template", template);
    handleClose();
  };

  const handleManageTemplates = () => {
    emit("manage-templates");
  };

  // 组件卸载时恢复body滚动
  onUnmounted(() => {
    handleBodyScroll(false);
  });

  // 暴露方法供父组件调用
  defineExpose({
    open: () => {
      visible.value = true;
      handleBodyScroll(true);
      fetchTemplates(true);
    },
    close: () => {
      visible.value = false;
      handleBodyScroll(false);
    },
  });
</script>

<style scoped lang="scss">
  .create-project-dialog {
    .el-dialog__body {
      padding: 20px 24px;
      max-height: calc(85vh - 140px);
      // 自定义滚动条样式
      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;

        &:hover {
          background: #a8a8a8;
        }
      }
    }

    .el-dialog__footer {
      padding: 0 24px 20px;
      border-top: 1px solid #f0f1f3;
      margin-top: 20px;
      padding-top: 16px;
    }
  }
</style>

<style lang="scss">
  // 全局样式，确保弹窗打开时禁止背景滚动
  .el-dialog__wrapper {
    overflow: hidden !important;
  }

  .create-blank-section {
    margin-bottom: 24px;

    .blank-project-card {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
      height: 46px;
      border: 1px dashed #90b9ed;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      max-width: 320px;

      .blank-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #1aa1fb;
      }

      .blank-text {
        font-size: 14px;
        font-weight: 500;
        color: #1aa1fb;
      }
    }
  }

  .template-section {
    display: flow;
    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 4px;

      .section-title {
        font-size: 14px;
        color: #5e5e5e;
      }

      .template-manage-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #5e5e5e;
        font-size: 14px;
        padding: 0;
        cursor: pointer;

        .tools-icon {
          width: 16px;
          height: 16px;
        }
      }
    }

    .template-grid-container {
      max-height: 250px;
      overflow-y: auto;
      padding-right: 4px;
      padding-left: 4px;

      // 自定义滚动条样式
      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3px;

        &:hover {
          background: #a8a8a8;
        }
      }
    }

    .template-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      min-height: 200px;
      padding-bottom: var(--el-dialog-padding-primary);

      .template-card {
        border: 1px solid #e1e4e8;
        border-radius: 12px;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #fff;

        &:hover {
          box-shadow: 0px 10px 8px 0px #0003;
        }

        .template-preview {
          height: 140px;
          overflow: hidden;
          background: #f6f8fa;
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .template-bg {
          background-color: #f4f5f5;
          display: flex;
          justify-content: center;
          align-items: center;

          &-icon {
            width: 100px;
          }
        }

        .template-info {
          padding: 18px;

          .template-name {
            font-size: 16px;
            font-weight: 600;
            color: #1a1a1a;
            margin: 0;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          &:hover {
            .template-name {
              color: #1aa1fb;
            }
          }

          .template-description {
            font-size: 13px;
            color: #6a737d;
            margin: 0;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }
      }
    }

    .loading-more {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 20px;
      color: #42464e;
      font-size: 14px;
    }

    .no-more {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      color: #909399;
      font-size: 14px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
</style>

<style lang="scss">
  .create-project-dialog {
    padding-bottom: 0;
    padding-left: 0;
    padding-right: 0;

    .el-dialog__header {
      padding-left: 16px;
    }

    &.el-dialog {
      margin: 0 !important;
      position: fixed !important;
      top: 50% !important;
      left: 50% !important;
      transform: translate(-50%, -50%) !important;
      max-height: 95vh !important;
      border-radius: 4px !important;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15) !important;
      min-height: 402px;
      .el-dialog__body {
        max-height: calc(100vh - 140px) !important;
        // overflow-y: auto !important;
        padding-left: var(--el-dialog-padding-primary);
        padding-right: var(--el-dialog-padding-primary);
      }
    }
  }

  // 弹窗遮罩层样式
  .el-overlay {
    .el-overlay-dialog {
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
    }
  }
</style>
